package util

//关于token的所有操作
import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

// 密钥
func Getscret() string {
	return "your_secret_key"
}

// 生成token
func GenerateToken(secret string, pass string, name string, incode string, expire int64) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"pass":   pass,
		"name":   name,
		"incode": incode,
		"iat":    time.Now().Unix(),
		"exp":    time.Now().Add(time.Duration(expire) * time.Second).Unix(),
	})

	tokenString, err := token.SignedString([]byte(secret))
	if err != nil {
		return "", err
	}

	return tokenString, nil
}

// 解析token
func ParseToken(secret string, tokenString string) (jwt.MapClaims, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %!v(MISSING)", token.Header["alg"])
		}
		return []byte(secret), nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims, nil
	}

	return nil, fmt.Errorf("invalid token")
}
